package com.spotbook.ui;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.spotbook.R;
import com.spotbook.providers.Contract;

public class SpotDetailFragment extends Fragment implements
		LoaderCallbacks<Cursor> {
	TextView titleView;
	TextView summaryView;
	ImageView photoView;
	View progress;

	private Uri uri;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater
				.inflate(R.layout.fragment_spot_detail, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		this.titleView = (TextView) view.findViewById(android.R.id.title);
		this.summaryView = (TextView) view.findViewById(android.R.id.summary);
		this.photoView = (ImageView) view.findViewById(android.R.id.icon);
		this.progress = view.findViewById(android.R.id.progress);
	}

	public void setData(Uri uri) {
		this.uri = uri;
		getLoaderManager().restartLoader(0, null, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle extras) {
		return new CursorLoader(getActivity(), this.uri, null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (data.moveToFirst()) {
			ContentValues values = new ContentValues();
			DatabaseUtils.cursorRowToContentValues(data, values);
			final String name = values.getAsString(Contract._NAME);
			final String summary = values.getAsString(Contract._SUMMARY);
			final String filePath = values.getAsString(Contract._THUMBNAIL);
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					titleView.setText(name);
					summaryView.setText(summary);
					new LoadImageTask(filePath) {
						@Override
						protected void onPreExecute() {
							photoView
									.setImageResource(android.R.drawable.ic_menu_gallery);
							progress.setVisibility(View.VISIBLE);
						}

						@Override
						protected void onPostExecute(Bitmap result) {
							photoView.setImageBitmap(result);
							progress.setVisibility(View.INVISIBLE);
						}
					}.execute();
				}
			});
		} else {
			onLoaderReset(loader);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				titleView.setText(null);
				summaryView.setText(null);
				photoView.setImageResource(android.R.drawable.ic_menu_gallery);
			}
		});
	}
}
